<?php
namespace app\helpers;

/**
 * @desc 文件上传助手
 * @author lizichuan
 * @date 2018-6-13
 */
class FileUploader
{
	private $rootPath;
	
	public function __construct()
	{
		$this->rootPath = dirname(__DIR__).'/web/';
	}
	
	/**
	 * @desc 上传文件
	 * @param string $fieldName 表单的字段名称
	 * @return 上传后的服务器路径
	 * @date 2018-6-13
	 */
	public function upload($fieldName, $allowType = '')
	{
		$allowSize = 5*1024*1024;
		if (empty($allowType)) {
			$allowType = '|png|jpg|jpeg|gif|bmp|doc|xls|txt|zip|ppt|pdf|rar|docx|xlsx|pptx|';
		}
		else {
			$allowType = '|'.strtolower(trim($allowType, '|')).'|';
		}
		
		if (empty($_FILES[$fieldName])) {
			return '';
		}
		$upload = $_FILES[$fieldName];
		if (!empty($upload['error'])) {
			return '';
		}
		if (empty($upload['name'])) {
			return '';
		}
		$tmp_name = $upload['tmp_name'];
		if (!is_uploaded_file($tmp_name)) {
			return '';
		}
		if ($upload['size'] > $allowSize) {
			return '';
		}
		
		//后缀
		$suffix = '';
		$uploadName = $upload['name'];
		$index = strrpos($uploadName, '.');
		if ($index !== false) {
			$suffix = strtolower(substr($uploadName, $index+1));
		}
		if (strpos($allowType, '|'.$suffix.'|') === false) {
			return '';
		}
		
		//文件根目录
		$baseDir = $this->rootPath.'uploadfile/image/';
		if (!file_exists($baseDir)) {
			if (!mkdir($baseDir)) {
				return '';
			}
		}
		
		$fileName = date('Ymd_His').rand(10, 99) .'.'.$suffix;
		if (!move_uploaded_file($tmp_name, $baseDir.$fileName)) {
			return '';
		}
		
		return 'uploadfile/image/'.$fileName;
	}
}
